package com.centit.framework.ip.webservice.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.interfaces.Claim;
import com.centit.fileserver.client.DefaultFileClient;
import com.centit.fileserver.client.po.FileStoreInfo;
import com.centit.framework.common.JsonResultUtils;
import com.centit.framework.common.ResponseMapData;
import com.centit.framework.components.CodeRepositoryUtil;
import com.centit.framework.core.controller.BaseController;
import com.centit.framework.core.dao.CodeBook;
import com.centit.framework.ip.appversion.service.AppVersionManager;
import com.centit.framework.ip.businessdata.po.InterfaceLog;
import com.centit.framework.ip.businessdata.po.MessageInfo;
import com.centit.framework.ip.businessdata.po.TodoItem;
import com.centit.framework.ip.businessdata.service.InterfaceLogManager;
import com.centit.framework.ip.businessdata.service.InterfaceManagerManager;
import com.centit.framework.ip.businessdata.service.MessageInfoManager;
import com.centit.framework.ip.businessdata.service.TodoItemManager;
import com.centit.framework.ip.util.*;
import com.centit.framework.ip.webservice.po.ResponseResult;
import com.centit.framework.ip.webservice.service.BusinessDataService;
import com.centit.framework.model.adapter.PlatformEnvironment;
import com.centit.framework.model.basedata.IUserUnit;
import com.centit.framework.security.model.CentitPasswordEncoder;
import com.centit.framework.security.model.CentitUserDetails;
import com.centit.framework.system.po.OptInfo;
import com.centit.framework.system.po.UserInfo;
import com.centit.framework.system.po.UserRole;
import com.centit.framework.system.po.UserUnit;
import com.centit.framework.system.service.SysUserManager;
import com.centit.framework.system.service.SysUserRoleManager;
import com.centit.framework.system.service.SysUserUnitManager;
import com.centit.msgpusher.client.MsgPusherClientImpl;
import com.centit.support.algorithm.UuidOpt;
import com.centit.support.database.utils.PageDesc;
import com.centit.support.database.utils.QueryAndNamedParams;
import com.centit.support.database.utils.QueryUtils;
import com.centit.util.BaiduMap;
import com.centit.util.CommonDateUtil;
import com.centit.util.JwtToken;
import com.centit.util.LayuiResultUtil;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import javax.xml.crypto.Data;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Auther: 皇甫壮
 * @Date: 2018-5-16 10:09
 * @Description:业务数据调用的接口restful api方式
 */
@RestController
@RequestMapping({"/webservice/businessData"})
public class BusinessDataController extends BaseController {
    @Resource
    protected BusinessDataService businessDataService;
    @Resource
    protected InterfaceManagerManager interfaceManagerMag;
    @Resource
    protected InterfaceLogManager interfaceLogMag;
    @Resource
    @NotNull
    private SysUserManager sysUserManager;
    @Resource
    @NotNull
    private SysUserUnitManager sysUserUnitManager;
    @Resource
    @NotNull
    private SysUserRoleManager sysUserRoleManager;
    @Resource
    @NotNull
    private TodoItemManager todoItemMag;
    @Resource
    @NotNull
    private MessageInfoManager messageInfoMag;
    @Resource
    private CentitPasswordEncoder passwordEncoder;
    @Resource
    protected PlatformEnvironment platformEnvironment;
    @Resource
    private AppVersionManager appVersionManager;
    
    private DefaultFileClient fileClient;
    private static MsgPusherClientImpl client;
    private static String msgpushServerUrl= CodeRepositoryUtil.getSysConfigValue("msgpushServerUrl");
    private static String msgpushUsercode=CodeRepositoryUtil.getSysConfigValue("msgpushUsercode");
    private static String msgpushPwd=CodeRepositoryUtil.getSysConfigValue("msgpushPwd");
    private static String uploaderpath=CodeRepositoryUtil.getSysConfigValue("uploaderpath");

    public static void init(){

        client = new MsgPusherClientImpl();
    }
    public void setPasswordEncoder(CentitPasswordEncoder p) {
        this.passwordEncoder = p;
    }

    @RequestMapping(method = RequestMethod.GET)
    public String apiInfo() {
        return "this apis  businessData is work";
    }

    /**
     * 功能描述:
     *
     * @param: requestEntity 调用接口请求参数，包含客户端标识、业务标识、业务条件
     * @return: com.centit.framework.ip.webservice.po.ResponseResult<com.alibaba.fastjson.JSONArray>
     * @auther: 皇甫壮
     * @date: 2018-5-16 14:05
     * @Description:业务子系统之间数据交互通过当前接口，客户端子系统调用支撑平台（当前系统） 支撑平台根据
     * 1客户端标识，业务标识，身份认证，匹配业务所需的sql语句，
     * 2根据目标服务标识查询出目标服务地址
     * 3支撑平台转发返回目标服务的json数据
     * 4记录调用日志
     * 本方法不做中间件，样例是统一平台获取的数据
     */
    @RequestMapping(value = "/selfData", method = RequestMethod.POST)
    public ResponseResult<JSONArray> selfData(HttpEntity<String> requestEntity, HttpServletRequest request) {
        ResponseResult<JSONArray> result = new ResponseResult<JSONArray>();
        String bodyJson = requestEntity.getBody();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = JSONObject.parseObject(bodyJson, paramMap.getClass());
        //数据筛选MAP
        Map<String, Object> filterMap = new HashMap<String, Object>();
        //请求参数校验
        if (paramValid(paramMap)) {
            //请求数据结果JSON
            JSONArray jsonArray = new JSONArray();
            //请求结果标识
            String resultFlag = "T";
            //响应信息
            String responseStr = "";

            //客户端标识
            Object systemflag = paramMap.get("systemflag");
            //业务标识
            Object methodflag = paramMap.get("methodflag");
            //获取请求客户端IP
            String cliendIp = RequestUtil.getIpAddr(request);
            System.err.println("cliendIp->" + cliendIp);
            filterMap.put("systemflag", systemflag);
            filterMap.put("methodflag", methodflag);
            //测试阶段关闭IP校验
//            filterMap.put("systemurl", cliendIp);
            //filterMap.put("systemurl", "192.168.135.67");
            //获取相应的接口配置信息
            JSONObject jsonObject = this.interfaceManagerMag.getObjectAsJson(filterMap);
            if (null != jsonObject) {
                //获取响应数据
//                jsonArray = this.interfaceManagerMag.listObjectsBySqlAsJson(jsonObject.getString("sqlcontent"), paramMap, null);
                jsonArray = this.interfaceManagerMag.listBySqlAsJson(jsonObject.getString("sqlcontent"), paramMap);
                //返回数据
                result.setCode(String.valueOf(HttpStatus.OK));
                result.setData(jsonArray);

                responseStr = jsonArray.toString();
            } else {
                resultFlag = "F";
                responseStr = "未获取到响应信息";
                result.setCode(String.valueOf(HttpStatus.NOT_FOUND));
                result.setDesc(responseStr);
            }
            //保存调用记录
            InterfaceLog interfaceLog = new InterfaceLog();
            interfaceLog.setRecordid(UuidOpt.getUuidAsString());
            interfaceLog.setCreater(getLoginUserCode(request));
            interfaceLog.setCreateTime(new Date());
            interfaceLog.setMethodflag(String.valueOf(methodflag));
            interfaceLog.setSystemflag(String.valueOf(systemflag));
            interfaceLog.setYwflag("0");
            interfaceLog.setResultflag(resultFlag);
            interfaceLog.setResponse(responseStr);
            this.interfaceLogMag.saveNewObject(interfaceLog);
        } else {//请求数据异常
            result.setCode(String.valueOf(HttpStatus.BAD_REQUEST));
            result.setDesc("请求数据异常");
        }
        return result;
    }

    /**
     * 功能描述: 作为中间件数据获取转发,此方法仅供我们自己开发的子系统之间数据交互，第三方的服务端调用有待扩展
     *
     * @param: requestEntity 调用接口请求参数，包含客户端标识、业务标识、业务条件
     * @return: com.centit.framework.ip.webservice.po.ResponseResult<com.alibaba.fastjson.JSONArray>
     * @auther: 皇甫壮
     * @date: 2018-5-16 15:05
     */
    @RequestMapping(value = "/transmitData", method = RequestMethod.POST)
    public ResponseResult<JSONArray> transmitData(HttpEntity<String> requestEntity, HttpServletRequest request) {
        ResponseResult<JSONArray> result = new ResponseResult<JSONArray>();
        String bodyJson = requestEntity.getBody();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = JSONObject.parseObject(bodyJson, paramMap.getClass());
        //数据筛选MAP
        Map<String, Object> filterMap = new HashMap<String, Object>();
        //请求参数校验
        if (paramValid(paramMap)) {
            //请求数据结果JSON
            JSONArray jsonArray = new JSONArray();
            //请求结果标识
            String resultFlag = "T";
            //响应信息
            String responseStr = "";

            //客户端标识
            Object systemflag = paramMap.get("systemflag");
            //业务标识
            Object methodflag = paramMap.get("methodflag");
            //请求客户端IP
            String clientIp = RequestUtil.getIpAddr(request);
            filterMap.put("systemflag", systemflag);
            filterMap.put("methodflag", methodflag);
            filterMap.put("systemurl", clientIp);
            //获取相应的接口配置信息
            JSONObject jsonObject = this.interfaceManagerMag.getObjectAsJson(filterMap);
            if (null != jsonObject) {
                String sqlcontent = jsonObject.getString("sqlcontent");
                String methodurl = jsonObject.getString("methodurl");
                paramMap.put("sqlcontent", sqlcontent);
                //返回数据
                result = ClientRequestUtil.getRestTemplate().postForObject(methodurl, paramMap, ResponseResult.class);
                if (result == null) {
                    
                } else {
                    if ("200".equals(result.getCode())) {
                        resultFlag = "T";
                    }
                    //类型转换异常
                    responseStr = "类型转换异常";
                }
            } else {
                resultFlag = "F";
                responseStr = "未获取到响应信息";
                result.setCode(String.valueOf(HttpStatus.NOT_FOUND));
                result.setDesc(responseStr);
            }
            //保存调用记录
            InterfaceLog interfaceLog = new InterfaceLog();
            interfaceLog.setRecordid(UuidOpt.getUuidAsString());
            interfaceLog.setCreater(getLoginUserCode(request));
            interfaceLog.setCreateTime(new Date());
            interfaceLog.setMethodflag(String.valueOf(methodflag));
            interfaceLog.setSystemflag(String.valueOf(systemflag));
            interfaceLog.setYwflag("0");
            interfaceLog.setResultflag(resultFlag);
            interfaceLog.setResponse(responseStr);
            this.interfaceLogMag.saveNewObject(interfaceLog);
        } else {//请求数据异常
            result.setCode(String.valueOf(HttpStatus.BAD_REQUEST));
            result.setDesc("请求数据异常");
        }

        return result;
    }

/*
    *//**
     * 新增用户信息
     *
     * @param requestEntity 调用接口请求参数，包含用户信息，机构信息
     * @param request       HttpServletRequest
     * @param response      HttpServletResponse
     *//*
    @RequestMapping(value = "/saveUser", method = RequestMethod.POST)
    public ResponseResult<JSONArray> saveUser(HttpEntity<String> requestEntity,
                                               HttpServletRequest request, HttpServletResponse response) {

        ResponseResult<JSONArray> result = new ResponseResult<JSONArray>();
        try {
            String bodyJson = requestEntity.getBody();
            JSONArray jsonArray = JSONArray.parseArray(bodyJson);
            //用户信息
            UserInfo userInfo;
            //主机构信息
            UserUnit userUnit;
            //角色信息
            List<UserRole> userRoles;
            //其他机构信息
            List<UserUnit> userUnits;
            //返回的用户信息
            JSONArray userInfos = new JSONArray();
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                userInfo = JSONObject.parseObject(JSONObject.toJSONString(jsonObject.get("userInfo")), UserInfo.class);
                userUnit = JSONObject.parseObject(JSONObject.toJSONString(jsonObject.get("userUnit")), UserUnit.class);
                userRoles = JSONArray.parseArray(JSONObject.toJSONString(jsonObject.get("userRoles")), UserRole.class);
                userUnits = JSONArray.parseArray(JSONObject.toJSONString(jsonObject.get("userUnits")), UserUnit.class);
                //请求信息校验
                if(StringUtils.isBlank(userInfo.getLoginName())){//如果登陆名为空，默认用户的全拼
                	userInfo.setLoginName(pingyin.getPingYin(userInfo.getUserName()));
                }
                String errorMsg = userInfoValid(userInfo, userUnit);
                if (StringUtils.isNotEmpty(errorMsg)) {
                    result.setCode(String.valueOf(HttpStatus.PRECONDITION_FAILED));
                    result.setDesc(errorMsg);
                    return result;
                }
                //登录名唯一性校验
                UserInfo dbuserinfo = sysUserManager.loadUserByLoginname(userInfo.getLoginName());
                if (null != dbuserinfo) {
                    result.setCode(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR));
                    result.setDesc("登录名" + userInfo.getLoginName() + "已存在，请更换！");
                    return result;
                }
                //保存用户及主机构信息
                userUnit.setCreator(getLoginUserCode(request));
                sysUserManager.saveNewUserInfo(userInfo, userUnit);
                UserInfo afterUserinfo=sysUserManager.loadUserByLoginname(userInfo.getLoginName());//用户全信息
                //用户配置其他机构信息
                if (null != userUnits) {
                    HashMap<String, Object> map;
                    List<UserUnit> list;
                    for (UserUnit uu : userUnits) {
                        uu.setUserCode(userInfo.getUserCode());
                        map = new HashMap();
                        map.put("unitCode", uu.getUnitCode());
                        map.put("userRank", uu.getUserRank());
                        map.put("userCode", uu.getUserCode());
                        list = sysUserUnitManager.listObjects(map, new PageDesc());
                        if (list == null || list.size() == 0) {
                            uu.setCreator(getLoginUserCode(request));
                            uu.setIsPrimary("F");
                            uu.setCreateDate(new Date());
                            sysUserUnitManager.saveNewUserUnit(uu);
                        }
                    }
                }
                //配置角色信息
                if (null != userRoles) {
                    for (UserRole ur : userRoles) {
                        ur.setUserCode(userInfo.getUserCode());
                        ur.setObtainDate(new Date());
                        ur.setCreateDate(new Date());
                        sysUserRoleManager.mergeObject(ur);
                    }
                }
                //返回保存的用户信息
                userInfos.add(afterUserinfo);
                //记录日志
                InterfaceLog interfaceLog = new InterfaceLog();
                interfaceLog.setRecordid(UuidOpt.getUuidAsString());
                interfaceLog.setCreater(getLoginUserCode(request));
                interfaceLog.setCreateTime(new Date());
                interfaceLog.setMethodflag(String.valueOf("ZCPT"));
                interfaceLog.setSystemflag(String.valueOf("businessData_saveUser"));
                interfaceLog.setYwflag("0");
                interfaceLog.setResultflag("T");
                interfaceLog.setResponse(JSONObject.toJSONStringWithDateFormat(userInfo, "yyyy-MM-dd HH:mm:ss"));
                this.interfaceLogMag.saveNewObject(interfaceLog);
            }
            //返回信息
            result.setCode(String.valueOf(HttpStatus.OK));
            result.setDesc("操作成功");
            result.setData(userInfos);
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR));
            result.setDesc("操作异常");
        }
        return result;
    }*/


    /**
     * 子系统更新节点下所有待办事项数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "mergeToDoItem", method = RequestMethod.POST)
    public ResponseResult<JSONObject> mergeToDoItem(HttpEntity<String> requestEntity,
                                                    HttpServletRequest request, HttpServletResponse response) {
        //解析请求信息
        ResponseResult<JSONObject> result = new ResponseResult<JSONObject>();
        try {
            String bodyJson = requestEntity.getBody();
            JSONArray jsonArray = JSONArray.parseArray(bodyJson);
            String childRecId = null;
            if (null != jsonArray) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    childRecId = jsonArray.getString(i);
                    //更新数据
                    this.todoItemMag.updateObject(childRecId);
                    //记录调用日志
                    InterfaceLog interfaceLog = new InterfaceLog();
                    interfaceLog.setRecordid(UuidOpt.getUuidAsString());
                    interfaceLog.setCreater(getLoginUserCode(request));
                    interfaceLog.setCreateTime(new Date());
                    interfaceLog.setMethodflag(String.valueOf("ZCPT"));
                    interfaceLog.setSystemflag(String.valueOf("businessData_mergeToDoItem"));
                    interfaceLog.setYwflag("0");
                    interfaceLog.setResultflag("T");
                    this.interfaceLogMag.saveNewObject(interfaceLog);
                }
            }
            //返回响应信息
            result.setCode(String.valueOf(HttpStatus.OK));
            result.setDesc("待办更新成功");
        } catch (Exception e) {
            result.setCode(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR));
            result.setDesc("待办更新异常");
        }
        return result;
    }

    /**
     * 子系统更新待办事项数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "mergeToUserDoItem", method = RequestMethod.POST)
    public ResponseResult<JSONObject> mergeToUserDoItem(HttpEntity<String> requestEntity,
                                                        HttpServletRequest request, HttpServletResponse response) {
        //解析请求信息
        ResponseResult<JSONObject> result = new ResponseResult<JSONObject>();
        try {
            String bodyJson = requestEntity.getBody();
            JSONArray jsonArray = JSONArray.parseArray(bodyJson);
            String recId = null;
            if (null != jsonArray) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    recId = jsonArray.getString(i);
                    TodoItem todoItem = todoItemMag.getObjectById(recId);
                    todoItem.setIsValid("F");
                    todoItem.setUpdateTime(new Date());
                    //更新数据
                    this.todoItemMag.updateObject(todoItem);
                    //记录调用日志
                    InterfaceLog interfaceLog = new InterfaceLog();
                    interfaceLog.setRecordid(UuidOpt.getUuidAsString());
                    interfaceLog.setCreater(getLoginUserCode(request));
                    interfaceLog.setCreateTime(new Date());
                    interfaceLog.setMethodflag(String.valueOf("ZCPT"));
                    interfaceLog.setSystemflag(String.valueOf("businessData_mergeToDoItem"));
                    interfaceLog.setYwflag("0");
                    interfaceLog.setResultflag("T");
                    this.interfaceLogMag.saveNewObject(interfaceLog);
                }
            }
            //返回响应信息
            result.setCode(String.valueOf(HttpStatus.OK));
            result.setDesc("待办更新成功");
        } catch (Exception e) {
            result.setCode(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR));
            result.setDesc("待办更新异常");
        }
        return result;
    }

    /**
     * 子系统新增待办事项数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "saveToDoItem", method = RequestMethod.POST)
    public ResponseResult<JSONObject> saveToDoItem(HttpEntity<String> requestEntity,
                                                   HttpServletRequest request, HttpServletResponse response) {
        //解析请求信息
        ResponseResult<JSONObject> result = new ResponseResult<JSONObject>();
        try {
            String bodyJson = requestEntity.getBody();
            JSONArray jsonArray = JSONArray.parseArray(bodyJson);
            TodoItem todoItem = null;
            if (null != jsonArray) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    todoItem = jsonArray.getObject(i, TodoItem.class);
                    //新增数据
                    if (StringUtils.isBlank(todoItem.getRecId())) {
                        todoItem.setRecId(UuidOpt.getUuidAsString32());
                    }
                    todoItem.setCreateTime(new Date());
                    //删除重复数据
                    this.todoItemMag.deleteObjectById(todoItem.getRecId());
                    //保存待办数据
                    this.todoItemMag.saveNewObject(todoItem);
                    //记录调用日志
                    InterfaceLog interfaceLog = new InterfaceLog();
                    interfaceLog.setRecordid(UuidOpt.getUuidAsString());
                    interfaceLog.setCreater(getLoginUserCode(request));
                    interfaceLog.setCreateTime(new Date());
                    interfaceLog.setMethodflag(String.valueOf("ZCPT"));
                    interfaceLog.setSystemflag(String.valueOf("businessData_saveToDoItem"));
                    interfaceLog.setYwflag("0");
                    interfaceLog.setResultflag("T");
                    this.interfaceLogMag.saveNewObject(interfaceLog);
                }
            }
            //返回响应信息
            result.setCode(String.valueOf(HttpStatus.OK));
            result.setDesc("待办保存成功");
        } catch (Exception e) {
            result.setCode(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR));
            result.setDesc("请求信息异常");
        }
        return result;
    }

    /**
     * 子系统推送消息提醒数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/pushData", method = RequestMethod.POST)
    public ResponseResult<JSONObject> pushData(HttpEntity<String> requestEntity,
                                               HttpServletRequest request, HttpServletResponse response) {
        ResponseResult<JSONObject> result = new ResponseResult<JSONObject>();

        try {
            String bodyJson = requestEntity.getBody();
            JSONArray jsonArray = JSONArray.parseArray(bodyJson);
            MessageInfo messageInfo = null;
            if (null != jsonArray) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    //解析消息主体
                    messageInfo = jsonArray.getObject(i, MessageInfo.class);
                    if (null != messageInfo) {
                        //保存推送消息
                        MessageInfo messageInfoOrgin=messageInfoMag.getObjectById(messageInfo.getRecId());
                        if(messageInfoOrgin!=null){
                            messageInfoOrgin.copyNotNullProperty(messageInfo);
                            messageInfo=messageInfoOrgin;
                        }
                        this.messageInfoMag.mergeObject(messageInfo);
                        //记录调用日志
                        InterfaceLog interfaceLog = new InterfaceLog();
                        interfaceLog.setRecordid(UuidOpt.getUuidAsString());
                        interfaceLog.setCreater(getLoginUserCode(request));
                        interfaceLog.setCreateTime(new Date());
                        interfaceLog.setMethodflag(String.valueOf("ZCPT"));
                        interfaceLog.setSystemflag(String.valueOf("businessData_pushData"));
                        interfaceLog.setYwflag("0");
                        interfaceLog.setResultflag("T");
                        this.interfaceLogMag.saveNewObject(interfaceLog);
                        //返回响应信息
                        result.setCode(String.valueOf(HttpStatus.OK));
                        result.setDesc("操作成功");
                    } else {
                        result.setCode(String.valueOf(HttpStatus.PRECONDITION_FAILED));
                        result.setDesc("请求参数解析异常");
                    }
                }
            }
        } catch (Exception e) {
//            e.printStackTrace();
            result.setCode(String.valueOf(HttpStatus.INTERNAL_SERVER_ERROR));
            result.setDesc("请求信息异常");
        }
        return result;
    }

    /**
     * 功能描述: 手机端用户登录第一个调用方法
     *
     * @param:需要传设备Id
     * @return:返回RAS公钥
     * @auther: 皇甫壮
     * @date: 2018-6-28 13:28
     */
    @RequestMapping(value = "/appRsaKey", method = RequestMethod.POST)
    public ResponseResult<String> appRsaKey(HttpEntity<String> requestEntity, HttpServletRequest request) {
        ResponseResult<String> result = new ResponseResult<String>();
        String bodyJson = requestEntity.getBody();
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap = ClientRequestUtil.URLRequest(bodyJson);// URLRequest JSONObject.parseObject(bodyJson, paramMap.getClass());
        String devId = (String) paramMap.get("devId");
        Map<String, Object> keyMap;
        try {
            keyMap = CreateSecrteKey.initKey();
            String publicKey = CreateSecrteKey.getPublicKey(keyMap);//获取rsa公钥
            result.setCode(String.valueOf(HttpStatus.OK));
            result.setData(publicKey); //返回公钥
            System.out.println("公钥：" + publicKey);
            String privateKey = CreateSecrteKey.getPrivateKey(keyMap);//获取rsa私钥
            System.out.println("私钥加入缓存：" + privateKey);
            result.setDesc(privateKey);
            //内存管理器
            CacheManager cacheManager = CacheManager.newInstance();
            //建立一个缓存实例
            Cache memoryOnlyCache = null;
            //在内存管理器中添加缓存实例
            Element element = new Element("privateKey", privateKey);
            memoryOnlyCache = new Cache(devId, 5000, false, false, 60, 60);
            cacheManager.removeCache(memoryOnlyCache.getName());//去除同名称的 devid设备主键，唯一，对于每个用户
            cacheManager.addCache(memoryOnlyCache);//本行和下面那行两行顺序不能颠倒
            memoryOnlyCache.put(element);
            //记录调用日志
            InterfaceLog interfaceLog = new InterfaceLog();
            interfaceLog.setRecordid(UuidOpt.getUuidAsString());
            interfaceLog.setCreater(getLoginUserCode(request));
            interfaceLog.setCreateTime(new Date());
            interfaceLog.setMethodflag("appRsaKey");
            interfaceLog.setSystemflag("appLoginKey");
            interfaceLog.setResponse("publicKey:" + publicKey + ";privateKey:" + privateKey);
            interfaceLog.setYwflag("0");
            interfaceLog.setResultflag("T");
            this.interfaceLogMag.saveNewObject(interfaceLog);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 功能描述: 用户名密码登录
     *
     * @param:登录名，密码经过服务器端第一次返回的公钥加密之后的，客户端生成的RSA公钥
     * @return:
     * @auther: 皇甫壮
     * @date: 2018-6-28 13:31
     *//*
    @RequestMapping(value = "/appLogin", method = RequestMethod.POST)
    public ResponseResult<JSONArray> appLogin(HttpEntity<String> requestEntity, HttpServletRequest request) {
        ResponseResult<JSONArray> result = new ResponseResult<JSONArray>();
        String bodyJson = requestEntity.getBody();
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap = ClientRequestUtil.URLRequest(bodyJson);
        JSONObject json = JSONObject.parseObject(bodyJson);
        String devId=(String) paramMap.get("devId");
        String loginName=(String) paramMap.get("loginName"); //app端用户的登录名称
        String pwd=(String) paramMap.get("pwd");//经过服务器返回第一次连接时返回的公钥加密之后的密码
        String devId = (String) json.get("devId");
        String loginName = (String) json.get("loginName"); 
        Pattern p = Pattern.compile("\\s*|\t|\r|\n");
		Matcher m = p.matcher(loginName);
		loginName = m.replaceAll("");
        String pwd = (String) json.get("pwd");
        CacheManager cacheManager = CacheManager.newInstance();
        Cache cache = cacheManager.getCache(devId);
        //使用缓存
         Element element = cache.get("privateKey");
        String  privateKey= element.getValue().toString();//取出私钥准备解密密码
        try {
            System.out.println("接收到的：" + pwd);
             byte[] pwd1=CreateSecrteKey.decryptByPrivateKey(pwd.getBytes(),privateKey);//私钥解密之后的得到正确的密码
           // 传加密数据时使用
            //pwd = Des3.decode(pwd);
        } catch (Exception e) {
            e.printStackTrace();
        }
        UserInfo userInfo = sysUserManager.loadUserByLoginname(loginName);
        String code = "0";
        String desc = "登录成功";
        if (userInfo != null) {
            Boolean enBool = passwordEncoder.isPasswordValid(userInfo.getUserPin(),
                    pwd, userInfo.getUserCode()); passwordEncoder.encodePassword(pwd,userInfo.getUserCode());
            if (enBool) {
                try {
                    JSONObject jsonObject = new JSONObject();
                    JSONArray jsonArray = new JSONArray();
                    String token = JwtToken.createToken(userInfo.getUserCode(), userInfo.getLoginName());
                    String primaryUnit = userInfo.getPrimaryUnit();
                    String primaryName = CodeRepositoryUtil.getUnitName(primaryUnit);
                    String zw= "";
                    String sql="select t.xrzw,t.name from personnel.t_rsgl_ryxx t where 1=1 [:usercode| and t.user_code=:usercode]";
                    Map<String ,Object> filterMap=new HashMap<String ,Object>();
                    filterMap.put("usercode",userInfo.getUserCode());
                    QueryAndNamedParams params= QueryUtils.translateQuery(
                            sql, null,
                            filterMap, true);
                    //人事系统人员职务
                    JSONArray jsonArrayzw=messageInfoMag.listObjectsBySqlAsJson(params.getQuery(),params.getParams(),null);
                    if(jsonArrayzw!=null&&jsonArrayzw.size()>0){
                        zw=jsonArrayzw.getJSONObject(0).getString("xrzw");
                    }
                    List<? extends IUserUnit>  userSettings =CodeRepositoryUtil.listUserUnits(userInfo.getUserCode());
                    String wldcode= CodeRepositoryUtil.getValue("TYPZ","wld");
                    if(userSettings!=null&&userSettings.size()>0){
                        for (IUserUnit item:userSettings){
                            if (wldcode.equals(item.getUnitCode())){//属于委领导部门,查询工作流的人员分组
                                sql="select t.code,t1.name from apprflow.task_leader t ,apprflow.task_leader_group t1  where t.groupid=t1.rec_id " +
                                        "[:usercode| and t.code=:usercode]";
                                params= QueryUtils.translateQuery(
                                        sql, null,
                                        filterMap, true);
                                jsonArrayzw=messageInfoMag.listObjectsBySqlAsJson(params.getQuery(),params.getParams(),null);
                                if(jsonArrayzw!=null&&jsonArrayzw.size()>0){
                                    primaryName=jsonArrayzw.getJSONObject(0).getString("name");
                                }
                                break;
                            }
                        }
                    }
                    JSONObject objStrs = adminInforManager.getByUserPhone(loginName);
                    String userType = "0";//其他人员
                    String citys = "";
                    String districts = "";
                    String towns = "";
                    String villagess = "";
                    if(objStrs!=null&&!objStrs.isEmpty()) {
                    	if(objStrs.getString("userType").indexOf("网格长")>-1) {
                    		userType = "1";//网格长
                    	}else if (objStrs.getString("userType").indexOf("网格员")>-1) {
                    		userType = "2";//网格员
                    	}else if(objStrs.getString("userType").indexOf("供热站联络员")>-1) {
                    		userType = "3";//供热站联络员
                    	}else if(objStrs.getString("userType").indexOf("配送中心联络员")>-1) {
                    		userType = "4";//配送中心联络员
                    	}else if(objStrs.getString("userType").indexOf("省级部门联络员")>-1) {
                    		userType = "5";//省级部门联络员
                    	}
                    	citys = objStrs.containsKey("city")?objStrs.getString("city"):"";
                		towns = objStrs.containsKey("town")?objStrs.getString("town"):"";
                		districts = objStrs.containsKey("district")?objStrs.getString("district"):"";
                		villagess = objStrs.containsKey("villages")?objStrs.getString("villages"):"";
                    }
                    boolean flag = true;
                    if(objStrs!=null&&!objStrs.isEmpty()) {
                    	 flag = true;
                    }else {
                    	 flag = false;
                    }
                    int zhs =  residentCoalMag.getTjData(flag,citys,districts,villagess);
                    jsonObject.put("userType",userType);
                    jsonObject.put("city",citys);
                    jsonObject.put("town",towns);
                    jsonObject.put("district",districts);
                    jsonObject.put("villages",villagess);
                    jsonObject.put("token", token);
                    jsonObject.put("usercode",userInfo.getUserCode());
                    jsonObject.put("username",userInfo.getUserName());
                    jsonObject.put("unitname",primaryName);
                    jsonObject.put("zw",zw);
                    jsonObject.put("zhs",zhs);
                    jsonObject.put("yzl",zhs);
                    jsonObject.put("wzl",0);
                    jsonArray.add(jsonObject);
                    result.setData(jsonArray);
                    //建立一个缓存实例
                    Cache memoryOnlyCache = null;
                    //在内存管理器中添加缓存实例
                    Element elementToekn = new Element("token", token);
                    memoryOnlyCache = new Cache(devId, 5000, false, false, 0, 3600);
                    cacheManager.removeCache(memoryOnlyCache.getName());//去除同名称的 devid设备主键，唯一，对于每个用户
                    cacheManager.addCache(memoryOnlyCache);//本行和下面那行两行顺序不能颠倒
                    memoryOnlyCache.put(elementToekn);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                code = "1";
                desc = "用户密码不正确";
            }
        } else {
            code = "1";
            desc = "用户登录名不存在";
        }
        result.setCode(code);
        result.setDesc(desc);
        //记录调用日志
        InterfaceLog interfaceLog = new InterfaceLog();
        interfaceLog.setRecordid(UuidOpt.getUuidAsString());
        interfaceLog.setCreater(getLoginUserCode(request));
        interfaceLog.setCreateTime(new Date());
        interfaceLog.setMethodflag("appRsaKey");
        interfaceLog.setSystemflag("appLoginKey");
        interfaceLog.setResponse("code:" + code + ";desc:" + desc);
        interfaceLog.setYwflag("0");
        interfaceLog.setResultflag("T");
        this.interfaceLogMag.saveNewObject(interfaceLog);
        return result;
    }
    *//**
     * 功能描述: 手机端用户登录成功之后，注册channelId
     *
     * @param:需要传设备Id,channelId
     * @return:返回信息
     * @auther: 皇甫壮
     * @date: 2018-6-28 13:28
     *//*
    @RequestMapping(value = "/registerChannelId", method = RequestMethod.POST)
    public ResponseResult<JSONObject> registerChannelId(HttpEntity<String> requestEntity, HttpServletRequest request) {
        ResponseResult<JSONObject> result = new ResponseResult<JSONObject>();
        String bodyJson = requestEntity.getBody();
        JSONObject json = JSONObject.parseObject(bodyJson);
        String devId = (String) json.get("devId");
        String channelId = (String) json.get("channelId");
        String usercode = (String) json.get("usercode");
        try {
            //登录成功注册app用户
            if(client==null){
            init();
            }
            client.initAppSession(msgpushServerUrl,msgpushUsercode,msgpushUsercode);
            //app安卓端用户注册（必须）
            String jsonStr = client.registerUser(usercode,"osId", devId, "3", channelId);
            ResponseJSON resJson = ResponseJSON.valueOfJson(jsonStr);
            result.setCode(String.valueOf(resJson.getCode()));
            result.setData((JSONObject) resJson.getData());
            //记录调用日志
            InterfaceLog interfaceLog = new InterfaceLog();
            interfaceLog.setRecordid(UuidOpt.getUuidAsString());
            interfaceLog.setCreater(usercode);
            interfaceLog.setCreateTime(new Date());
            interfaceLog.setMethodflag("registerChannelId");
            interfaceLog.setSystemflag("registerChannelId");
            interfaceLog.setResponse(JSON.toJSONString(resJson));
            interfaceLog.setYwflag("0");
            interfaceLog.setResultflag("T");
            this.interfaceLogMag.saveNewObject(interfaceLog);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    *//**
     *
     * 功能描述:app端获取待办信息
     *
     * @param:
     * @return:
     * @auther: 皇甫壮
     * @date: 2018-8-27 10:45
     *//*
    @RequestMapping(value = "/getDbInfo", method = RequestMethod.POST)
    public void getDbInfo(HttpEntity<String> requestEntity, HttpServletRequest request, HttpServletResponse response){
        String bodyJson = requestEntity.getBody();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = JSONObject.parseObject(bodyJson, paramMap.getClass());
        if(paramMap==null){
            paramMap = new HashMap<String, Object>();
        }
        String token = (String) paramMap.get("token");
        Map<String, Claim> claims = JwtToken.verifyToken(token);
        Claim usercode_claim = claims.get("usercode");
        String userCode = usercode_claim.asString();
        Map<String, Object> filterMap=new HashMap<String, Object>();
        String sql=" select itemState,count(1) from  T_TODO_ITEM  where isValid='T' [:USER_CODE| and USER_CODE=:USER_CODE] and itemState is not null  group by itemState";
        filterMap.put("USER_CODE",userCode);
        QueryAndNamedParams params = QueryUtils.translateQuery(sql, filterMap);
        JSONArray jsonArray=todoItemMag.listObjectsBySqlAsJson(params.getQuery(),params.getParams(),null);
        ResponseMapData resData = new ResponseMapData();
        resData.addResponseData(OBJLIST, jsonArray);
        JsonResultUtils.writeResponseDataAsJson(resData, response);
    }
    *//**
     *
     * 功能描述: 获取菜单信息app接口
     *
     * @param:
     * @return:
     * @auther: 皇甫壮
     * @date: 2018-8-27 11:08
     *//*
    @RequestMapping(value = "/getOptInfo", method = RequestMethod.POST)
    public void getOptInfo(HttpEntity<String> requestEntity, HttpServletRequest request, HttpServletResponse response){
        String bodyJson = requestEntity.getBody();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = JSONObject.parseObject(bodyJson, paramMap.getClass());
        if(paramMap==null){
            paramMap = new HashMap<String, Object>();
        }
        String token = (String) paramMap.get("token");
        Map<String, Claim> claims = JwtToken.verifyToken(token);
        Claim usercode_claim = claims.get("usercode");
        String userCode = usercode_claim.asString();
        List<OptInfo> menus=null;
        if(StringUtils.isNotBlank(userCode)){
            menus =(List<OptInfo>) platformEnvironment.listUserMenuOptInfos(userCode,
                    false);
        }else{
            menus=null;
        }
        StringBuilder stringBuilder = layuiResultUtil.getStringMenu(menus,new StringBuilder());
        ResponseMapData resData = new ResponseMapData();
        resData.addResponseData(OBJLIST, stringBuilder.toString());
        JsonResultUtils.writeResponseDataAsJson(resData, response);
    }
    *//**
     *
     * 功能描述:获取app推送历史消息
     *
     * @param:
     * @return:
     * @auther: 皇甫壮
     * @date: 2018-8-28 21:01
     *//*
    @RequestMapping(value = "/getAppInfo", method = RequestMethod.POST)
    public void getAppInfo(HttpEntity<String> requestEntity, HttpServletRequest request, HttpServletResponse response){
        String bodyJson = requestEntity.getBody();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = JSONObject.parseObject(bodyJson, paramMap.getClass());
        if(paramMap==null){
            paramMap = new HashMap<String, Object>();
        }
        String userCode=null;
        String token = (String) paramMap.get("token");
        String pageno = (String) paramMap.get("pageno");
        String pagesize = (String) paramMap.get("pagesize");
        String ifread=(String) paramMap.get("ifread");
        PageDesc pageDesc = new PageDesc();
        pageDesc.setPageNo(Integer.valueOf(pageno));
        pageDesc.setPageSize(Integer.valueOf(pagesize));
        if(StringUtils.isNotBlank(token)){
        Map<String, Claim> claims = JwtToken.verifyToken(token);
        Claim usercode_claim = claims.get("usercode");
         userCode = usercode_claim.asString();
        }
        Map<String, Object> filterMap=new HashMap<String, Object>();
        ifread= StringEscapeUtils.escapeHtml(ifread);
        ifread=StringEscapeUtils.escapeJavaScript(ifread);
        String sql=" select msg_id,nvl(user_name,msg_sender) msg_sender,user_name,msg_receiver,msg_subject,msg_content,push_time,os_id, opt_id,nvl(ifread,1)ifread from f_message_delivery  left join f_userinfo " +
                " on msg_sender=user_code " +
                "where notice_types='A' and push_state='3' [:msg_receiver| and msg_receiver=:msg_receiver]";
        if("0".equals(ifread)){//已读
               sql+=" [:ifread| and ifread=:ifread] ";
              filterMap.put("ifread",ifread);
        }else if("1".equals(ifread)){//未读
            sql+=" [:ifread| and (ifread=:ifread or ifread is null)] ";
            filterMap.put("ifread",ifread);
        }
        sql+=  " order by nvl(ifread,1),push_time desc  ";

        filterMap.put("msg_receiver",userCode);
        QueryAndNamedParams params = QueryUtils.translateQuery(sql, filterMap);
        JSONArray jsonArray=todoItemMag.listObjectsBySqlAsJson(params.getQuery(),params.getParams(),pageDesc);
        ResponseMapData resData = new ResponseMapData();
        resData.addResponseData(OBJLIST, jsonArray);
        JsonResultUtils.writeResponseDataAsJson(resData, response);
    }
    *//**
     *
     * 功能描述: app获取未读信息条数
     *
     * @param:
     * @return:
     * @auther: 皇甫壮
     * @date: 2018-9-10 20:04
     *//*
    @RequestMapping(value = "/getAppInfoWdcount", method = RequestMethod.POST)
    public void getAppInfoWdcount(HttpEntity<String> requestEntity, HttpServletRequest request, HttpServletResponse response){
        String bodyJson = requestEntity.getBody();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = JSONObject.parseObject(bodyJson, paramMap.getClass());
        if(paramMap==null){
            paramMap = new HashMap<String, Object>();
        }
        String userCode=null;
        String token = (String) paramMap.get("token");
        if(StringUtils.isNotBlank(token)){
            Map<String, Claim> claims = JwtToken.verifyToken(token);
            Claim usercode_claim = claims.get("usercode");
            userCode = usercode_claim.asString();
        }
        JSONObject jsonObject=new JSONObject();
        //查询是否有未读消息条数
        Map<String, Object> filterMap=new HashMap<String, Object>();
        String sql=" select count(1) countnum from f_message_delivery  left join f_userinfo " +
                " on msg_sender=user_code where notice_types='A' and push_state='3' [:msg_receiver| and msg_receiver=:msg_receiver]";
        sql+=" [:ifread| and (ifread=:ifread or ifread is null)] ";
        filterMap.put("ifread","1");
        sql+=  " order by nvl(ifread,1),push_time desc  ";
        filterMap.put("msg_receiver",userCode);
        QueryAndNamedParams params = QueryUtils.translateQuery(sql, filterMap);
        JSONArray appNoread=todoItemMag.listObjectsBySqlAsJson(params.getQuery(),params.getParams(),null);
        jsonObject.put("countnum",appNoread.getJSONObject(0).getString("countnum"));
        JsonResultUtils.writeSingleDataJson(jsonObject, response);
    }
*/

    /**
     *
     * 功能描述:获取推送信息单条信息
     *
     * @param:
     * @return:
     * @auther: 皇甫壮
     * @date: 2018-9-8 15:13
     */
    @RequestMapping(value = "/getAppInfoOne", method = RequestMethod.POST)
    public void getAppInfoOne(HttpEntity<String> requestEntity, HttpServletRequest request, HttpServletResponse response){
        String bodyJson = requestEntity.getBody();
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = JSONObject.parseObject(bodyJson, paramMap.getClass());
        if(paramMap==null){
            paramMap = new HashMap<String, Object>();
        }
        String userCode=null;
        String token = (String) paramMap.get("token");
        String msg_id=(String) paramMap.get("msg_id");
        if(StringUtils.isNotBlank(token)){
            Map<String, Claim> claims = JwtToken.verifyToken(token);
            Claim usercode_claim = claims.get("usercode");
            userCode = usercode_claim.asString();
        }
        Map<String, Object> filterMap=new HashMap<String, Object>();
        msg_id= StringEscapeUtils.escapeHtml(msg_id);
        msg_id=StringEscapeUtils.escapeJavaScript(msg_id);
        String sql=" select msg_id,nvl(t.user_name,msg_sender) msg_sender,t1.user_name msg_receiver,msg_subject,msg_content,push_time,os_id, opt_id from f_message_delivery  " +
                " left join f_userinfo t on msg_sender=t.user_code " +
                " left join f_userinfo t1 on msg_receiver=t1.user_code " +
                " where notice_types='A' [:msg_id| and msg_id=:msg_id] [:msg_receiver| and msg_receiver=:msg_receiver]"
                ;
        filterMap.put("msg_id",msg_id);
        filterMap.put("msg_receiver",userCode);
        QueryAndNamedParams params = QueryUtils.translateQuery(sql, filterMap);
        JSONArray jsonArray=todoItemMag.listObjectsBySqlAsJson(params.getQuery(),params.getParams(),null);
        ResponseMapData resData = new ResponseMapData();
        resData.addResponseData(OBJLIST, jsonArray);
        //更新成已读
        if(jsonArray!=null&&jsonArray.size()>0){
            sql=" update f_message_delivery set ifread='0' where 1=1 and msg_id=? and msg_receiver=?";
            messageInfoMag.updateBysql(sql,new Object[]{msg_id,userCode});
        }
        JsonResultUtils.writeResponseDataAsJson(resData, response);
    }

    @RequestMapping(value = "/getAppMaxVersion", method = RequestMethod.POST)
    public void getAppMaxVersion(HttpEntity<String> requestEntity, HttpServletRequest request, HttpServletResponse response){
        Map<String, Object> searchColumn = convertSearchColumn(request);
        searchColumn.put(CodeBook.SELF_ORDER_BY," to_number(versionno) desc");
        JSONArray jsonArrayObjects = appVersionManager.listObjectsAsJson( searchColumn, null);
        JSONObject jsonObject=new JSONObject();
        if(jsonArrayObjects!=null&&jsonArrayObjects.size()>0){
            jsonObject=jsonArrayObjects.getJSONObject(0);
            jsonObject.put("downAppUrl",uploaderpath+"/service/download/pfile/"+jsonObject.get("fileid"));
        }
        JsonResultUtils.writeSingleDataJson(jsonObject, response);
    }

    /**
     *
     * 功能描述:获取文件信息
     *
     * @param:
     * @return: 
     * @auther: 皇甫壮
     * @date: 2018-8-16 11:12
     */
    @RequestMapping(value = "/getFileInfo", method = RequestMethod.GET)
    public ResponseResult<JSONArray> getFileInfo(HttpEntity<String> requestEntity, HttpServletRequest request) {
        ResponseResult<JSONArray> result = new ResponseResult<JSONArray>();
        String bodyJson = requestEntity.getBody();
        JSONObject json = JSONObject.parseObject(bodyJson);
        String devId = (String) json.get("devId");
        String channelId = (String) json.get("channelId");
        String usercode = (String) json.get("usercode");
        String fileIds=(String) json.get("fileIds");
        //获取fileClient值
        fileClient=FileUploadUtil.getFileClient();
        JSONArray jsonArray=new JSONArray();
        try {
            String[] fileId=null;
            if(StringUtils.isNotBlank(fileIds)){
                fileId=fileIds.split(",");
            }
            if(fileId!=null&&fileId.length>0){
                FileStoreInfo fileStoreInfo;
                JSONObject jsonObject;
                for (int i=0;i<fileId.length;i++){
                    fileStoreInfo=fileClient.getFileStoreInfo(fileClient.getHttpClient(),fileId[i]);
                    jsonObject=new JSONObject();
                    jsonObject.put("fileId",fileStoreInfo.getFileId());
                    jsonObject.put("fileName",fileStoreInfo.getFileName());
                    jsonObject.put("fileUrl",uploaderpath+"/service/download/pfile/"+fileStoreInfo.getFileId());
                    jsonArray.add(jsonObject);
                }
            }
            result.setCode("0");
            result.setData(jsonArray);
            //记录调用日志
            InterfaceLog interfaceLog = new InterfaceLog();
            interfaceLog.setRecordid(UuidOpt.getUuidAsString());
            interfaceLog.setCreater(usercode);
            interfaceLog.setCreateTime(new Date());
            interfaceLog.setMethodflag("getFileInfo");
            interfaceLog.setSystemflag("getFileInfo");
            interfaceLog.setResponse("app获取文件信息");
            interfaceLog.setYwflag("0");
            interfaceLog.setResultflag("T");
            this.interfaceLogMag.saveNewObject(interfaceLog);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 校验请求参数
     *
     * @param paramMap
     * @return
     */
    private boolean paramValid(Map<String, Object> paramMap) {
        //校验请求参数是否含有客户端标识及业务标识
        if (paramMap.containsKey("systemflag") && paramMap.containsKey("methodflag")) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 用户信息校验
     *
     * @param userInfo 用户信息
     * @param userUnit 机构信息
     * @return
     */
    private String userInfoValid(UserInfo userInfo, UserUnit userUnit) {
        String errorMsg = null;
        if (null != userInfo && null != userUnit) {
            if (StringUtils.isEmpty(userInfo.getLoginName())) {
                errorMsg = "用户信息：登录名缺失";
            } else if (StringUtils.isEmpty(userInfo.getUserName())) {
                errorMsg = "用户信息：用户名缺失";
            } else if (StringUtils.isEmpty(userInfo.getPrimaryUnit())) {
                errorMsg = "用户信息：主机构缺失";
            } else if (StringUtils.isEmpty(userInfo.getIsValid())) {
                errorMsg = "用户信息：用户状态缺失";
            } else if (StringUtils.isEmpty(userUnit.getUserRank())) {
                errorMsg = "机构信息：行政职务缺失";
            } else if (StringUtils.isEmpty(userUnit.getUserStation())) {
                errorMsg = "机构信息：岗位缺失";
            }
        } else {
            errorMsg = "请求信息异常";
        }
        return errorMsg;
    }

    /**
     * 功能描述: 验证token
     * 各子系统传递数据给app移动端的时候需要调用此接口验证登录信息
     *
     * @param:
     * @return:
     * @auther: 皇甫壮
     * @date: 2018-7-2 14:47
     */
    @RequestMapping(value = "/validToken", method = RequestMethod.POST)
    public ResponseResult<String> validToken(HttpEntity<String> requestEntity, HttpServletRequest request) {
        ResponseResult<String> result = new ResponseResult<String>();
        String bodyJson = requestEntity.getBody();
        // Map<String, String> paramMap = new HashMap<String, String>();
        //paramMap = ClientRequestUtil.URLRequest(bodyJson);// URLRequest JSONObject.parseObject(bodyJson, paramMap.getClass());
        JSONObject json = JSONObject.parseObject(bodyJson);
        String devId = (String) json.get("devId");
        String token = (String) json.get("token");
        boolean tokenIf = this.valid(token, devId);
        String code = "0";
        String desc = "令牌存在";
        if (tokenIf) {

        } else {
            code = "1";
            desc = "令牌不存在，没有访问权限";
        }
        result.setCode(code);
        result.setDesc(desc);
        try {
            //记录调用日志
            InterfaceLog interfaceLog = new InterfaceLog();
            interfaceLog.setRecordid(UuidOpt.getUuidAsString());
            interfaceLog.setCreater(getLoginUserCode(request));
            interfaceLog.setCreateTime(new Date());
            interfaceLog.setMethodflag("appRsaKey");
            interfaceLog.setSystemflag("validToken");
            interfaceLog.setResponse("code:" + code + ";desc:" + desc);
            interfaceLog.setYwflag("0");
            interfaceLog.setResultflag("T");
            this.interfaceLogMag.saveNewObject(interfaceLog);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 功能描述:
     *
     * @param: app端注销，清除token
     * @return:
     * @auther: 皇甫壮
     * @date: 2018-7-2 16:09
     */
    @RequestMapping(value = "/logoutToken", method = RequestMethod.POST)
    public ResponseResult<String> logoutToken(HttpEntity<String> requestEntity, HttpServletRequest request) {
        ResponseResult<String> result = new ResponseResult<String>();
        String bodyJson = requestEntity.getBody();
        // Map<String, String> paramMap = new HashMap<String, String>();
        //paramMap = ClientRequestUtil.URLRequest(bodyJson);// URLRequest JSONObject.parseObject(bodyJson, paramMap.getClass());
        JSONObject json = JSONObject.parseObject(bodyJson);
        String devId = (String) json.get("devId");
        String token = (String) json.get("token");
        CacheManager cacheManager = CacheManager.newInstance();
        cacheManager.removeCache(devId);
        String code = "0";
        String desc = "注销成功";
        result.setCode(code);
        result.setDesc(desc);
        try {
            //记录调用日志
            InterfaceLog interfaceLog = new InterfaceLog();
            interfaceLog.setRecordid(UuidOpt.getUuidAsString());
            interfaceLog.setCreater(getLoginUserCode(request));
            interfaceLog.setCreateTime(new Date());
            interfaceLog.setMethodflag("appRsaKey");
            interfaceLog.setSystemflag("validToken");
            interfaceLog.setResponse("code:" + code + ";desc:" + desc);
            interfaceLog.setYwflag("0");
            interfaceLog.setResultflag("T");
            this.interfaceLogMag.saveNewObject(interfaceLog);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public boolean valid(String token, String devId) {
        CacheManager cacheManager = CacheManager.newInstance();
        Cache cache = cacheManager.getCache(devId);
        //使用缓存
        Element element = cache.get("token");
        String cachetoken = element.getValue().toString();//取出token
        if (token.equals(cachetoken)) {
            return true;
        } else {
            return false;
        }
    }
    
    public static void wToPdfChange(String wordFile,String pdfFile){//wordFile word 的路径  //pdfFile pdf 的路径 
    	          
    	          ActiveXComponent app = null;
    	             System.out.println("开始转换...");
    	             // 开始时间
    	           // long start = System.currentTimeMillis();  
    	             try {
    	              // 打开word
    	              app = new ActiveXComponent("Word.Application");
    	             // 获得word中所有打开的文档
    	             Dispatch documents = app.getProperty("Documents").toDispatch();
    	             System.out.println("打开文件: " + wordFile);
    	             // 打开文档
    	             Dispatch document = Dispatch.call(documents, "Open", wordFile, false, true).toDispatch();
    	             // 如果文件存在的话，不会覆盖，会直接报错，所以我们需要判断文件是否存在
    	             File target = new File(pdfFile);  
    	              if (target.exists()) {  
    	                 target.delete();
    	              }
    	             System.out.println("另存为: " + pdfFile);
    	             Dispatch.call(document, "SaveAs", pdfFile, 17);
    	             // 关闭文档
    	             Dispatch.call(document, "Close", false);
    	            }catch(Exception e) {
    	             System.out.println("转换失败"+e.getMessage());
    	            }finally {
    	              // 关闭office
    	             app.invoke("Quit", 0);
    	            }
    	     }
    
    @RequestMapping(value = "/openFile", method = RequestMethod.GET)
	public void openFile(HttpServletRequest request, HttpServletResponse response) throws IOException  {
	   	String fileId=request.getParameter("fileId");
	   	String file="d:/TEMPFILE/"+fileId;
	   	String pdfFile="d:/TEMPFILE/"+fileId+".pdf";
	   	downloadNet(fileId);
    	wToPdfChange(file, pdfFile);
    	String urlPath = "";
		response.reset();
		response.setContentType("application/octet-stream");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Content-Disposition", "attachment;filename=" + fileId+".pdf");
		byte[] buff = new byte[1024];
		BufferedInputStream bis = null;
		OutputStream os = null;
		try {
			FileInputStream fis=new FileInputStream(pdfFile);
			os = response.getOutputStream();
            //获得PDF文件流
			System.out.println("获取流结束。。。。");
			bis = new BufferedInputStream(fis);
			int i = 0;
			while ((i = bis.read(buff)) != -1) {
				os.write(buff, 0, i);
				os.flush();
			}
 
		} catch (Exception e) {
			logger.error("pdf处理出现异常：" + e.getMessage() + "; ");
		} finally {
			try {
				bis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
    
   
    public void downloadNet(String fileId) throws MalformedURLException {
        // 下载网络文件
        int bytesum = 0;
        int byteread = 0;
        String urlStr=uploaderpath+"/service/download/pfile/"+fileId;
        URL url = new URL(urlStr);

        try {
            URLConnection conn = url.openConnection();
            InputStream inStream = conn.getInputStream();
            FileOutputStream fs = new FileOutputStream("d:/TEMPFILE/"+fileId);

            byte[] buffer = new byte[1204];
            int length;
            while ((byteread = inStream.read(buffer)) != -1) {
                bytesum += byteread;
                System.out.println(bytesum);
                fs.write(buffer, 0, byteread);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
	
}